import { defineStore } from "pinia";
import cookie from "js-cookie";
import router from "@/router";
import { post } from "@/utils/http";
import { ElMessage } from 'element-plus'
export const useUserStore = defineStore({
    id:'useStore',
    persist:{
        paths:['user','loginInfo']
    }, //持久化
    state:()=>({
        user: new UserInfo(),  //用户信息
        loginInfo:{
            username:'' ,//用户名
            password:'' //密码
        }
    }),
    actions:{
        setUser(user:UserInfo){
            this.user = user
        },
        loginOut() {
            let that = this
            const data = {
                _gp: 'admin',
                _mt: 'logout'
            }
            post(data).then((res: any) => {
                if (200 == res.errno) {
                    ElMessage.success("退出成功")
                    that.user = new UserInfo()   //将存储的数据清空
                    cookie.remove('token')//清除令牌
                    router.replace('/login')//跳转到登录页面
                } else {
                    ElMessage.error(res.errmsg)
                }
            })
         }
    },
    getters:{
        /**
         * 用户权限列表
         * @param state 状态管理仓库
         * @returns 权限列表    
         */
        permissionList:(state)=>{
            return state.user.perms;
        }
    }
})

class UserInfo {
    avatarUrl?:string;
    gmtCreate:number;
    gmtLastLogin:string;
    gmtUpdate:number;
    id:number;
    lastLoginIp:string;
    perms:string[];
    phone:string;
    realname:string;
    roleIds:number[];
    roles:string[];
    status:number;
    username:string;
    constructor(){
        this.avatarUrl = "";
        this.gmtCreate = 0;
        this.gmtLastLogin = "";
        this.gmtUpdate = 0;
        this.id = 0;
        this.lastLoginIp = "";
        this.perms = [];
        this.phone = "";
        this.realname = "";
        this.roleIds = [];
        this.roles = [];
        this.status = 0;
        this.username = "";
    }
}